'use client'

import React, { useState, useCallback } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Plus,
  MapPin,
  Trash2,
  Edit3,
  Save,
  X,
  Building2,
  Navigation
} from 'lucide-react'
import { toast } from 'sonner'
import { AddressSearchInput } from './AddressSearchInput'
import { AMAP_KEY } from '@/lib/config'
import { hospitalAPI, HospitalSite as APIHospitalSite } from '@/lib/api/hospital'

interface HospitalSite {
  id: string
  name: string
  center: [number, number]
  zoom: number
  address?: string
  district?: string
  city?: string
  province?: string
}

interface SearchResult {
  id: string
  name: string
  address: string
  location: [number, number]
  district?: string
  city?: string
  province?: string
}

interface HospitalSiteManagerProps {
  sites: HospitalSite[]
  onSitesChange: (sites: HospitalSite[]) => void
  currentSiteId?: string
  onSiteSelect: (siteId: string) => void
  className?: string
}

export const HospitalSiteManager: React.FC<HospitalSiteManagerProps> = ({
  sites,
  onSitesChange,
  currentSiteId,
  onSiteSelect,
  className = ""
}) => {
  const [isAdding, setIsAdding] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editingName, setEditingName] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  // 添加新医院站点
  const handleAddSite = useCallback(async (location: [number, number], address: string, result: SearchResult) => {
    console.log('添加站点:', { location, address, result })
    setIsLoading(true)

    try {
      const siteData = {
        name: result.name,
        address,
        coordinates: {
          longitude: location[0],
          latitude: location[1]
        },
        zoom: 16,
        district: result.district,
        city: result.city,
        province: result.province,
        status: 'active' as const
      }

      const response = await hospitalAPI.createSite(siteData)
      
      if (response?.success && response?.data) {
        // 转换API数据格式为本地格式
        const newSite: HospitalSite = {
          id: response.data.siteId,
          name: response.data.name,
          center: [response.data.coordinates.longitude, response.data.coordinates.latitude],
          zoom: response.data.zoom || 16,
          address: response.data.address,
          district: response.data.district,
          city: response.data.city,
          province: response.data.province
        }

        const updatedSites = [...sites, newSite]
        onSitesChange(updatedSites)
        setIsAdding(false)

        // 自动选择新添加的站点
        onSiteSelect(newSite.id)

        toast.success(`已添加医院站点：${newSite.name}`)
        console.log('站点添加成功:', newSite)
      }
    } catch (error) {
      console.error('添加站点失败:', error)
      toast.error('添加站点失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }, [sites, onSitesChange, onSiteSelect])

  // 删除站点
  const handleDeleteSite = useCallback(async (siteId: string) => {
    const site = sites.find(s => s.id === siteId)
    if (!site) return

    setIsLoading(true)

    try {
      const response = await hospitalAPI.deleteSite(siteId)
      
      if (response?.success) {
        const updatedSites = sites.filter(s => s.id !== siteId)
        onSitesChange(updatedSites)

        // 如果删除的是当前选中的站点，选择第一个站点
        if (currentSiteId === siteId && updatedSites.length > 0) {
          onSiteSelect(updatedSites[0].id)
        }

        toast.success(`已删除医院站点：${site.name}`)
      }
    } catch (error) {
      console.error('删除站点失败:', error)
      toast.error('删除站点失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }, [sites, onSitesChange, currentSiteId, onSiteSelect])

  // 开始编辑站点名称
  const startEditing = useCallback((site: HospitalSite) => {
    setEditingId(site.id)
    setEditingName(site.name)
  }, [])

  // 保存编辑
  const saveEditing = useCallback(async () => {
    if (!editingId || !editingName.trim()) return

    setIsLoading(true)

    try {
      const response = await hospitalAPI.updateSite(editingId, {
        name: editingName.trim()
      })
      
      if (response?.success) {
        const updatedSites = sites.map(site =>
          site.id === editingId
            ? { ...site, name: editingName.trim() }
            : site
        )

        onSitesChange(updatedSites)
        setEditingId(null)
        setEditingName('')

        toast.success('站点名称已更新')
      }
    } catch (error) {
      console.error('更新站点失败:', error)
      toast.error('更新站点失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }, [editingId, editingName, sites, onSitesChange])

  // 取消编辑
  const cancelEditing = useCallback(() => {
    setEditingId(null)
    setEditingName('')
  }, [])

  return (
    <Card className={`${className} overflow-hidden flex flex-col h-full`}>
      <CardHeader className="pb-3 flex-shrink-0">
        <div className="flex items-center justify-between">
          <CardTitle className="text-white text-lg flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-blue-500/20 border border-blue-400/30">
              <Building2 className="w-4 h-4 text-blue-300" />
            </div>
            医院站点管理
          </CardTitle>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setIsAdding(!isAdding)}
            disabled={isLoading}
            className={`flex items-center gap-2 transition-all duration-200 ${isAdding
                ? 'bg-red-500/20 border-red-400/30 text-red-300 hover:bg-red-500/30'
                : 'bg-blue-500/20 border-blue-400/30 text-blue-300 hover:bg-blue-500/30'
              } ${isLoading ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            {isAdding ? (
              <>
                <X className="w-4 h-4" />
                取消添加
              </>
            ) : (
              <>
                <Plus className="w-4 h-4" />
                添加站点
              </>
            )}
          </Button>
        </div>
      </CardHeader>

      <CardContent className="flex-1 flex flex-col">
        <div className="flex-1 space-y-4 pr-2 relative max-h-[280px] overflow-y-auto custom-scrollbar" style={{ overflowX: 'visible' }}>
          {sites.length > 2 && (
            <div className="absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-black/20 to-transparent pointer-events-none z-10 rounded-b-lg"></div>
          )}
          {/* 添加新站点 */}
          {isAdding && (
            <div className="p-4 rounded-xl bg-gradient-to-br from-blue-500/10 to-cyan-500/5 border border-blue-400/20 backdrop-blur-sm space-y-3 animate-in slide-in-from-top duration-200 relative" style={{ zIndex: 10000 }}>
              <div className="flex items-center justify-between">
                <Label className="text-white text-sm font-medium flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse"></div>
                  搜索并添加医院
                </Label>
              </div>
              <AddressSearchInput
                amapKey={AMAP_KEY}
                onLocationSelect={handleAddSite}
                placeholder="搜索医院名称或地址..."
                city="全国"
                showCurrentLocation={false}
              />
              <p className="text-xs text-white/60 flex items-center gap-2">
                <MapPin className="w-3 h-3" />
                输入医院名称或地址，从搜索结果中选择要添加的医院
              </p>
            </div>
          )}

          {/* 站点列表 */}
          <div className="space-y-3">
            {sites.length === 0 ? (
              <div className="text-center py-8 text-white/60">
                <div className="relative">
                  <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gradient-to-br from-blue-500/20 to-cyan-500/20 border border-blue-400/30 flex items-center justify-center">
                    <Building2 className="w-8 h-8 text-blue-300" />
                  </div>
                  <div className="absolute -top-1 -right-1 w-6 h-6 bg-blue-500/30 rounded-full animate-ping"></div>
                </div>
                <div className="font-medium text-white text-lg">暂无医院站点</div>
                <div className="text-sm mt-2 text-white/50">点击"添加站点"来添加第一个医院</div>
              </div>
            ) : (
              sites.map((site) => (
                <div
                  key={site.id}
                  className={`group relative p-4 rounded-xl border transition-all duration-200 cursor-pointer hover:scale-[1.02] ${currentSiteId === site.id
                      ? 'border-blue-400/50 bg-gradient-to-br from-blue-500/20 to-cyan-500/10 shadow-lg shadow-blue-500/10'
                      : 'border-white/20 bg-white/5 hover:border-white/30 hover:bg-white/10'
                    }`}
                  onClick={() => onSiteSelect(site.id)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      {editingId === site.id ? (
                        <div className="flex items-center gap-2 mb-2">
                          <Input
                            value={editingName}
                            onChange={(e) => setEditingName(e.target.value)}
                            className="h-8 text-sm"
                            placeholder="输入站点名称"
                            onKeyDown={(e) => {
                              if (e.key === 'Enter') saveEditing()
                              if (e.key === 'Escape') cancelEditing()
                            }}
                            autoFocus
                          />
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation()
                              saveEditing()
                            }}
                            className="h-8 w-8 p-0 text-green-600 hover:text-green-700"
                          >
                            <Save className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation()
                              cancelEditing()
                            }}
                            className="h-8 w-8 p-0 text-gray-500 hover:text-gray-700"
                          >
                            <X className="w-4 h-4" />
                          </Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-3 mb-2">
                          <div className="flex items-center gap-2 flex-1 min-w-0">
                            <div className="p-1.5 rounded-lg bg-green-500/20 border border-green-400/30">
                              <Building2 className="w-3 h-3 text-green-300" />
                            </div>
                            <h3 className="font-medium text-white truncate">
                              {site.name}
                            </h3>
                          </div>
                          {currentSiteId === site.id && (
                            <Badge className="text-xs bg-blue-500/20 border-blue-400/30 text-blue-300 animate-pulse">
                              <div className="w-1.5 h-1.5 rounded-full bg-blue-400 mr-1"></div>
                              当前
                            </Badge>
                          )}
                        </div>
                      )}

                      {site.address && (
                        <div className="flex items-start gap-2 text-sm text-white/70 mb-2">
                          <MapPin className="w-3 h-3 mt-0.5 flex-shrink-0 text-green-400" />
                          <span className="truncate">{site.address}</span>
                        </div>
                      )}

                      <div className="flex items-center gap-4 text-xs text-white/50">
                        <span className="flex items-center gap-1">
                          <Navigation className="w-3 h-3" />
                          {site.center[0].toFixed(4)}, {site.center[1].toFixed(4)}
                        </span>
                        {site.city && site.district && (
                          <span className="px-2 py-0.5 rounded bg-white/10 border border-white/20">
                            {site.city} {site.district}
                          </span>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center gap-1 ml-3">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          // 测试定位功能
                          console.log('测试站点定位:', site)
                          onSiteSelect(site.id)
                          toast.info(`正在定位到：${site.name}`)
                        }}
                        className="h-8 w-8 p-0 text-white/60 hover:text-green-400 hover:bg-green-500/20 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                        title="测试定位"
                      >
                        <Navigation className="w-3.5 h-3.5" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          startEditing(site)
                        }}
                        className="h-8 w-8 p-0 text-white/60 hover:text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                        title="编辑名称"
                      >
                        <Edit3 className="w-3.5 h-3.5" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          if (confirm(`确定要删除站点"${site.name}"吗？`)) {
                            handleDeleteSite(site.id)
                          }
                        }}
                        className="h-8 w-8 p-0 text-white/60 hover:text-red-400 hover:bg-red-500/20 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                        title="删除站点"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

        </div>

        {/* 底部统计 - 固定位置 */}
        {sites.length > 0 && (
          <div className="mt-4 pt-4 border-t border-white/10 flex-shrink-0">
            <div className="flex items-center justify-center gap-2 text-xs text-white/60">
              <div className="flex items-center gap-1">
                <div className="w-2 h-2 rounded-full bg-blue-400"></div>
                <span>共 {sites.length} 个医院站点</span>
              </div>
              {currentSiteId && (
                <>
                  <span className="text-white/30">•</span>
                  <div className="flex items-center gap-1">
                    <div className="w-2 h-2 rounded-full bg-green-400 animate-pulse"></div>
                    <span>已选择 {sites.find(s => s.id === currentSiteId)?.name}</span>
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

export default HospitalSiteManager